<template>
  <div class="cesium-map">
    <div id="cesiumContainer"></div>
  </div>
</template>

<script>
import { addLayer } from './map';
export default {
  data() {
    return {};
  },

  methods: {
    // 初始化地图
    createdMap() {
      var cesiumTerrainProvider = new Cesium.CesiumTerrainProvider({
        url: window.serviceUrl.terrainUrl,
        type: "xyz",
      });
      this.viewer = new Cesium.Viewer('cesiumContainer', {
        terrainProvider: cesiumTerrainProvider,
        contextOptions: {
          webgl: {
            alpha: true,
            depth: true,
            stencil: true,
            antialias: true
          }
        },
        useBrowserRecommendedResolution: true,
        selectionIndicator: false,
        homeButton: false,
        animation: false,  //是否显示动画控件
        baseLayerPicker: false, //是否显示图层选择控件
        geocoder: false, //是否显示地名查找控件
        timeline: false, //是否显示时间线控件
        sceneModePicker: false, //是否显示投影方式控件
        navigationHelpButton: false, //是否显示帮助信息控件
        infoBox: false,  //是否显示点击要素之后显示的信息
        imageryProvider: false,
        fullscreenButton: false,
        shouldAnimate: true,
        requestRenderMode: true,
      });
      this.viewer.scene.globe.depthTestAgainstTerrain = false;
      this.viewer.scene.primitives.destroyPrimitives = false;
      this.viewer.scene.postProcessStages._fxaa.enabled = true;
      this.viewer.scene.screenSpaceCameraController.enableCollisionDetection = true;
      this.viewer._cesiumWidget._creditContainer.style.display = "none";
      this.viewer.scene.globe.baseColor = Cesium.Color.BLACK;
      // this.viewer.scene.skyAtmosphere.show = false
      // this.viewer.scene.globe._surface.tileProvider._debug.wireframe = true;

      var handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
      handler.setInputAction((movement) => {
        var pickedObject = this.viewer.scene.pick(movement.position);
        var cartesian;
        if (!pickedObject) {
          if (this.viewer.scene.globe.depthTestAgainstTerrain) {
            cartesian = this.viewer.scene.pickPosition(movement.position);
          } else {
            //如果没开启深度检测
            var pickRay = this.viewer.scene.camera.getPickRay(movement.position);
            cartesian = this.viewer.scene.globe.pick(pickRay, this.viewer.scene);
          }
        } else {
          cartesian = this.viewer.scene.pickPosition(movement.position);
        }

        var ellipsoid = this.viewer.scene.globe.ellipsoid;
        var cartographic = ellipsoid.cartesianToCartographic(cartesian);
        var lat = Cesium.Math.toDegrees(cartographic.latitude);
        var lng = Cesium.Math.toDegrees(cartographic.longitude);
        var height = cartographic.height;
        console.log(lng + "," + lat + "," + height);
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

      //指北针
      let options = {};
      // 用于在使用重置导航重置地图视图时设置默认视图控制。接受的值是Cesium.Cartographic 和 Cesium.Rectangle.
      options.defaultResetView = Cesium.Rectangle.fromDegrees(80, 22, 130, 50);
      // 用于启用或禁用罗盘。true是启用罗盘，false是禁用罗盘。默认值为true。如果将选项设置为false，则罗盘将不会添加到地图中。
      options.enableCompass = true;
      // 用于启用或禁用缩放控件。true是启用，false是禁用。默认值为true。如果将选项设置为false，则缩放控件将不会添加到地图中。
      options.enableZoomControls = false;
      // 用于启用或禁用距离图例。true是启用，false是禁用。默认值为true。如果将选项设置为false，距离图例将不会添加到地图中。
      options.enableDistanceLegend = false;
      // 用于启用或禁用指南针外环。true是启用，false是禁用。默认值为true。如果将选项设置为false，则该环将可见但无效。
      options.enableCompassOuterRing = true;
      CesiumNavigation.umd(this.viewer, options);

      this.Global.viewer = this.viewer;
      // this.Global.viewer.camera.flyTo({
      //   destination: Cesium.Cartesian3.fromDegrees(114.965135, 30.432992, 1627.724367140964), //设置位置
      //   orientation: {
      //     heading: Cesium.Math.toRadians(0),
      //     pitch: Cesium.Math.toRadians(-90),
      //     roll: 0
      //   }
      // });

      //基础底图
      this.addBuildLayer();
      this.loadXZQ();
      this.loadzh();
      this.loadsq();
      this.$emit('loadComplete');
    },
    addBuildLayer() {
      this.baseLayer = addLayer(this.Global.viewer, window.serviceUrl.baseLayer);
      let layer = new Custom.HouseTileServiceImageryProvider(this.Global.viewer, {
        url: window.serviceUrl.baseFangwu,
        tilingScheme: new Cesium.GeographicTilingScheme({ numberOfLevelZeroTilesX: 2, numberOfLevelZeroTilesY: 1 }),
        tileMatrixLabels: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22"],
        // translucentMaterial: true,
        maximumLevel: 20,
        tileWidth: 256,
        tileHeight: 256,
        needDecode: false, // 是否需要数据解码
        // translucent: true,
        // opacity: 0.8,
        dataType: 'binary',
        fillColor: '#FFFFFF', // 房屋颜色
        translucent: false,
        opacity: 1, // 房屋透明度
        filterLayerId: ['房屋101'], // 房屋图层
        heightProperty: 'truez', // 房屋高度字段
        heightScale: 1,
        showLevel: 13,
      });
      this.Global.houseTileServiceImageryProvider = this.Global.viewer.imageryLayers.addImageryProvider(layer);
    },

    // 加载行政区划边界线
    loadXZQ() {
      this.$get('./data/黄冈市边界.json').then((res) => {
        const geojson = new Custom.Geojson().read(res);
        let geometryInstances = [];
        let xzqLine = [];
        geojson.lineArray.forEach((item) => {
          let positions = Cesium.Cartesian3.fromDegreesArray(item.geometry);

          // const line = this.viewer.scene.primitives.add(
          //   new Cesium.GroundPolylinePrimitive({//贴地primitive线
          //     geometryInstances: new Cesium.GeometryInstance({
          //       geometry: new Cesium.GroundPolylineGeometry({//贴地线几何
          //         positions: Cesium.Cartesian3.fromDegreesArray(item.geometry),
          //         width: 5,
          //       })
          //     }),
          //     appearance: new Cesium.PolylineMaterialAppearance({
          //       material: Cesium.Material.fromType('Color', {
          //         color: Cesium.Color.fromCssColorString('#DAA520'),
          //       })
          //     })
          //   }),
          // );
          // xzqLine.push(line);

          let maximumHeights = [];
          let minimumHeights = [];
          positions.forEach((i) => {
            maximumHeights.push(500);
            minimumHeights.push(0);
          });
          let geometryInstance = new Cesium.GeometryInstance({
            geometry: new Cesium.WallGeometry({
              positions: positions,
              maximumHeights: maximumHeights,
              minimumHeights: minimumHeights
            })
          });
          geometryInstances.push(geometryInstance);

          // let thickWall = new Cesium.Entity({
          //   polylineVolume: {
          //     positions: positions,
          //     shape: [  // 截面形状
          //       new Cesium.Cartesian2(-1 * 50, -0.5 * 500),
          //       new Cesium.Cartesian2(50, -0.5 * 500),
          //       new Cesium.Cartesian2(50, 0.5 * 500),
          //       new Cesium.Cartesian2(-1 * 50, 0.5 * 500)
          //     ],
          //     cornerType: Cesium.CornerType.MITERED,  // 线段转折处样式
          //     material: Cesium.Color.fromCssColorString("#DAA520").withAlpha(0.6),
          //   },
          // })
          // this.Global.viewer.entities.add(thickWall);
        });
        this.xzqLine = xzqLine;

        this.xzqWall = new Cesium['Primitive']({
          geometryInstances: geometryInstances,
          appearance: new Cesium.MaterialAppearance({
            material: Cesium.Material.fromType(Custom.DynamicGlowMaterialProperty.prototype.getType(), {
              color: Cesium.Color.fromCssColorString('#51E9FF').withAlpha(0.8),
              speed: 8,
              image: 'img/fence.png',
              axisY: true
            })
          }),
          asynchronous: false,
          modelMatrix: null,
          classificationType: 0
        });
        this.viewer.scene.primitives.add(this.xzqWall);
      });
    },

    loadzh() {
      this.$get('data/中环ln.json').then((res) => {
        const geojson = new Custom.Geojson().read(res);
        let geometryInstances = [];
        geojson.lineArray.forEach((item) => {
          let positions = Cesium.Cartesian3.fromDegreesArray(item.geometry);


          let maximumHeights = [];
          let minimumHeights = [];
          positions.forEach((i) => {
            maximumHeights.push(30);
            minimumHeights.push(0);
          });
          let geometryInstance = new Cesium.GeometryInstance({
            geometry: new Cesium.WallGeometry({
              positions: positions,
              maximumHeights: maximumHeights,
              minimumHeights: minimumHeights
            })
          });
          geometryInstances.push(geometryInstance);

        });

        this.Global.zhWall = new Cesium['Primitive']({
          geometryInstances: geometryInstances,
          appearance: new Cesium.MaterialAppearance({
            material: Cesium.Material.fromType(Custom.DynamicGlowMaterialProperty.prototype.getType(), {
              color: Cesium.Color.fromCssColorString('#51E9FF').withAlpha(0.8),
              speed: 8,
              image: 'img/fence.png',
              axisY: true
            })
          }),
          asynchronous: false,
          modelMatrix: null,
          classificationType: 0
        });
        this.viewer.scene.primitives.add(this.Global.zhWall);
        this.Global.zhWall.show = false;
      });

    },
    loadsq() {
      this.$get('data/三清社区ln.json').then((res) => {
        const geojson = new Custom.Geojson().read(res);
        let geometryInstances = [];
        geojson.polygonArray.forEach((item) => {
          let positions = Cesium.Cartesian3.fromDegreesArray(item.geometry.pts);

          let maximumHeights = [];
          let minimumHeights = [];
          positions.forEach((i) => {
            maximumHeights.push(30);
            minimumHeights.push(0);
          });
          let geometryInstance = new Cesium.GeometryInstance({
            geometry: new Cesium.WallGeometry({
              positions: positions,
              maximumHeights: maximumHeights,
              minimumHeights: minimumHeights
            })
          });
          geometryInstances.push(geometryInstance);

        });

        this.Global.sqWall = new Cesium['Primitive']({
          geometryInstances: geometryInstances,
          appearance: new Cesium.MaterialAppearance({
            material: Cesium.Material.fromType(Custom.DynamicGlowMaterialProperty.prototype.getType(), {
              color: Cesium.Color.fromCssColorString('#51E9FF').withAlpha(0.8),
              speed: 8,
              image: 'img/fence.png',
              axisY: true
            })
          }),
          asynchronous: false,
          modelMatrix: null,
          classificationType: 0
        });
        this.viewer.scene.primitives.add(this.Global.sqWall);
      });
    },

    removeXZQ() {
      this.xzqLine = removePrimitives(this.viewer, this.xzqLine);
      this.xzqWall = removePrimitives(this.viewer, this.xzqWall);;
    },
  },

  created() {
    this.viewer = null;
    this.baseLayer = null;
    this.xzqLine = [];
    this.xzqWall = null;
    this.Global.zhWall = null;
    this.Global.sqWall = null;
    this.Global.houseTileServiceImageryProvider = null;
  },

  mounted() {
    this.createdMap();
  },

  beforeDestroy() {
    this.removeXZQ();
  }
}
</script>

<style lang="less" scoped>
.cesium-map,
#cesiumContainer {
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 10;
}
</style>

<style lang="less">
.compass {
  top: 30px;
  right: 20px;

  .compass-rotation-marker,
  .compass-outer-ring {
    width: 90%;
    height: 90%;
  }

  .compass-outer-ring {
    background: url(~@/assets/image/toolBar/zhibeizhen.png) no-repeat;
    background-size: 100% 100%;
    background-size: 100%;
  }

  .compass-outer-ring-background,
  .compass-gyro-background,
  .compass-gyro {
    display: none;
  }
}

.cesium-performanceDisplay-defaultContainer {
  display: none !important;
}
</style>